package base.aqs.countdownlatch;

import java.util.concurrent.CountDownLatch;

/**
 * @author chengzhang
 * 2021/8/24 19:44
 */
public class CountDownLatch01 {

    //两个子线程 所以构造函数传参为2
    private static volatile CountDownLatch countDownLatch = new CountDownLatch(2);

    /**
     * 业务场景：主线程中开启多个线程去并行执行任务，并且主线程需要等待所有的子线程只想完毕后进行汇总（可以使用join，但是不够灵活）
     */
    public static void main(String[] args) throws InterruptedException {

        //主线程调用ountDownLatch.await()后会被阻塞。
        //子线程执行完毕后调用 countDownLatch.countDown() 让countDownLatch内部计数器减一
        //所有子线程执行完毕并调用countDown()方法后计数器会变为0，这时候主线程的await方法才会返回

        Thread thread01 = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            System.out.println("child thread01 over");
        });

        Thread thread02 = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                countDownLatch.countDown();
            }
            System.out.println("child thread02 over");
        });


        //启动子线程
        thread01.start();
        thread02.start();

        System.out.println("wait all child thread over");

        //等待子线程执行完毕，返回
        countDownLatch.await();
        System.out.println("all child thread over");
    }


}
